package com.imedway.ihe.dtz.atna;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import org.openehealth.ipf.commons.audit.AuditContext;
import org.openehealth.ipf.commons.audit.queue.AbstractAuditMessageQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

import static java.util.Objects.requireNonNull;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/8/8
 */
public class FileAuditMessageQueue extends AbstractAuditMessageQueue {

    private Logger log;
    private static final String DEFAULT_LOGGER_NAME = "FILE-AUDIT";
    public static final String DEFAULT_FILE_PATH = "D:/ihe-audit-log.xml";

    public FileAuditMessageQueue() {
        setPretty(true);
        setLoggerName(DEFAULT_LOGGER_NAME);
    }

    public void setLoggerName(String loggerName) {
        this.log = LoggerFactory.getLogger(requireNonNull(loggerName));
    }

    @Override
    protected void handle(AuditContext auditContext, String auditRecord) {
    	log.info(auditRecord);
        if (auditRecord != null) {
            if (!FileUtil.exist(DEFAULT_FILE_PATH)) {
                File file = FileUtil.file(DEFAULT_FILE_PATH);
                FileUtil.writeUtf8String(StrUtil.format("=================================================== {} ===================================================", DateUtil.now()), file);
            } else {
                FileUtil.appendUtf8String(StrUtil.format("\n=================================================== {} ===================================================\n", DateUtil.now()), DEFAULT_FILE_PATH);
            }
            FileUtil.appendUtf8String(auditRecord, DEFAULT_FILE_PATH);
//            log.info(auditRecord);
        }
    }
}
